package com.ruoyi.web.controller.system;

import lombok.SneakyThrows;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.HashMap;
import java.util.Map;

@Component
//声明该类要处理的包路径
@ControllerAdvice("com.ruoyi.web.controller.system")
public class ResponseAdvice implements ResponseBodyAdvice {


    // 对response处理的具体方法
    @Override
    @SneakyThrows
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        RequestAttributes ra = RequestContextHolder.getRequestAttributes();
        String sessionId = ra.getSessionId();
        if (o.toString().contains("500")) {
            return o;
        }
        Map map1 = new HashMap();
        map1.put("cookie", sessionId);
        map1.put("code", 0);
        map1.put("msg", "成功");
        return map1;
    }


    // 选择哪些类，或哪些方法需要走beforeBodyWrite
    // 从arg0中可以获取方法名和类名
    // arg0.getMethod().getDeclaringClass().getName()为获取方法名
    @Override
    public boolean supports(MethodParameter arg0, Class arg1) {
        String name = arg0.getMethod().getName();
        //   boolean equals = "ajaxLogin".equals(arg0.getMethod().getDeclaringClass().getName());
        boolean equals = "ajaxLogin".equals(arg0.getMethod().getName());
        return equals;
    }
}
